from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from weibo.models import User, Message

def index(request):
	has_logged_in = False
	user = None
	if request.session.get('has_login', False):
		has_logged_in = True
		user_id = request.session['id']
		user = User.objects.get( pk = user_id )
	
	all_messages = Message.objects.order_by('published_time').reverse()
	paginator = Paginator( all_messages, 4)
	page_number = request.GET.get('page')
	try:
		current_page = paginator.page( page_number )
	except PageNotAnInteger :
		current_page = paginator.page( 1 )
	except EmptyPage :
		current_page = paginator.page( paginator.num_pages )
	
	return render(request, 'weibo/index.html' , \
					{'has_logged_in':has_logged_in,\
					'user':user, \
					'current_page':current_page} )

def login_html(request):
	return render(request,'weibo/login_template.html')
def register_html(request):
	return render(request,'weibo/register_template.html')

def register(request):
	try:
		name = request.POST['name']
		password = request.POST['password']
	except KeyError :
		return HttpResponse('shound not pass illegal value')

	try:
		User.objects.get( name = name )
	except User.DoesNotExist :
		new_user = User( name = name, password = password )
		new_user.save()

		request.session['has_login'] = True
		request.session['id'] = new_user.pk
		return HttpResponseRedirect( reverse('weibo:index') )
	else:
		return HttpResponse('name has already been registered')

def login(request):
	try:
		name = request.POST['name']
		password = request.POST['password']
	except KeyError:
		return HttpResponse('shound not pass illegal value')
	
	try:
		user = User.objects.get(name = name )
	except User.DoesNotExist :
		return HttpResponse('user name not exist')
	else:
		if user.password == password :
			request.session['has_login'] = True
			request.session['id'] = user.pk
			return HttpResponseRedirect( reverse('weibo:index') )
		else:
			return HttpResponse('wrong password')

def logout(request):
	try:
		request.session['has_login'] = False
		request.session['id'] = -1
	except KeyError:
		pass
	return HttpResponseRedirect( reverse('weibo:index') )

def addmessage(request):
	if not request.session['has_login'] :
		return HttpResponse('add message after login')
	user = User.objects.get( pk = request.session['id'] )
	new_message = Message( text = request.POST['message'], \
					published_time = timezone.now(), \
					author = user )
	new_message.save()
	return HttpResponseRedirect( reverse('weibo:index') )
					
